package servlet.PersonServlet;

import dao.PersonDAO;
import entity.PageBean;
import entity.PersonBean;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@WebServlet("/PersonListServlet")
public class PersonListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String name = "";
        String worknumber = "";
        String department = "";
        String worktime = "";
        String profession = "";
        if (req.getParameter("name") != null) name = req.getParameter("name");
        if (req.getParameter("worknumber") != null) worknumber = req.getParameter("worknumber");
        if (req.getParameter("department") != null) department = req.getParameter("department");
        if (req.getParameter("worktime") != null) worktime = req.getParameter("worktime");
        if (req.getParameter("profession") != null) profession = req.getParameter("profession");
        ArrayList<String> departmentList = new ArrayList<>();
        if (department.contains(",")) {
            String[] itemClassesArray = department.split(","); // 使用逗号作为分隔符进行拆分
            Collections.addAll(departmentList, itemClassesArray); // 将数组中的所有元素添加到列表中
        } else {
            departmentList.add(department);
        }
        PersonDAO dao = new PersonDAO();
        int pageCount = dao.findPageCount(name, worknumber, departmentList, worktime, profession);
        int curpage = 1;
        if (req.getParameter("page") != null) {
            String pg = req.getParameter("page");
            curpage = Integer.parseInt(pg);
        }
        int al = 0; //al为-1时表示上一页，为1时表示下一页，默认为0
        if (req.getParameter("alterpage") != null) {
            String alpg = req.getParameter("alterpage");
            al = Integer.parseInt(alpg);
        }
        PageBean pageBean = new PageBean(curpage, al, pageCount);
        List<PersonBean> taskList = dao.findTask(name, worknumber, departmentList, worktime, profession, pageBean.getCurPage());
        req.setAttribute("pageBean", pageBean);
        req.setAttribute("taskList", taskList);
        req.getRequestDispatcher("person_list.jsp").forward(req, resp);
    }
}
